package com.service;
/*
 * *
 *  * blog.coder4j.cn
 *  * Copyright (C) 2016-2019 All Rights Reserved.
 *
 */

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.VO.OnlineUser;
import com.VO.TalkRecordsVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bean.MessageText;
import com.controller.LoginController;
import com.dao.LoginDao;
import com.entity.TalkKiara;
import com.entity.TalkRecords;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.SpringConfigurator;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author buhao
 * @version WsServerEndpoint.java, v 0.1 2019-10-18 16:06 buhao
 */
@ServerEndpoint(value = "/myWs/{userId}")
@Component
public class WsServerEndpoint {

    private static TalkRecordsService talkRecordsService;

    private static LoginDao loginDao;

    private static TalkKiaraService talkKiaraService;

    private  static  RedisService redisService;

    @Autowired
    public void setTalkRecordsService(TalkRecordsService talkRecordsService){
        WsServerEndpoint.talkRecordsService=talkRecordsService;
    }
    @Autowired
    public void setTalkKiaraService(TalkKiaraService talkKiaraService){
        WsServerEndpoint.talkKiaraService=talkKiaraService;
    }

    @Resource
    public void setLoginDao(LoginDao loginDao){
        WsServerEndpoint.loginDao=loginDao;
    }

    @Autowired
    public void setRedisService(RedisService redisService){
        WsServerEndpoint.redisService=redisService;
    }


//  //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
//  private static int onlineCount = 0;
  //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话，可以使用Map来存放，其中Key可以为用户标识
  private static ConcurrentHashMap<String, WsServerEndpoint> webSocketSet = new ConcurrentHashMap<String, WsServerEndpoint>();
  //与某个客户端的连接会话，需要通过它来给客户端发送数据
  private Session session;
  //当前发消息的人员编号
  private String userno = "";
  /**
   * 连接成功
   *
   * @param session
   */
  @OnOpen
  public void onOpen(Session session, EndpointConfig config,@PathParam("userId")Integer userId) {
      Integer userKiaraId = loginDao.findUserKiaraId(userId);


      TalkKiara one = talkKiaraService.getOne(new LambdaQueryWrapper<TalkKiara>().eq(userKiaraId != null, TalkKiara::getId, userKiaraId));

      OnlineUser onlineUser=new OnlineUser();
      BeanUtils.copyProperties(one,onlineUser);

      redisService.addOnlineUser(onlineUser);

      //Integer useridd=userId;
 //TalkRecords talkRecords=new TalkRecords();
//      talkRecords.setStatus(2);
////      talkRecords.setContent("进入了聊天室");
//      TalkRecords talkRecords1=new TalkRecords();
//      BeanUtils.copyProperties(talkRecords,talkRecords1);
//      Long randowid=System.currentTimeMillis();
//      Integer uuid= randowid.intValue();
//      talkRecords1.setId(uuid);
//      talkRecords1.setUserId(useridd);
//      talkRecords1.setPostTime(new Date());
//      talkRecords1.setKiaraId(loginDao.findUserKiaraId(useridd));
//      TalkKiara byId2 = talkKiaraService.getById(talkRecords1.getKiaraId());
//      talkRecords1.setContent(byId2.getName()+" 进入聊天室");
//
//      boolean save = talkRecordsService.save(talkRecords1);
//      TalkRecords talkRecords2=talkRecordsService.getById(uuid);
//
//      TalkRecordsVO talkRecordsVO=new TalkRecordsVO();
//      talkRecordsVO.setId(talkRecords2.getId());
//      talkRecordsVO.setContent(talkRecords2.getContent());
//      talkRecordsVO.setStatus(talkRecords2.getStatus());
//      talkRecordsVO.setKiaraId(talkRecords2.getKiaraId());
//      talkRecordsVO.setUserId(talkRecords2.getUserId());
//      TalkKiara byId = talkKiaraService.getById(talkRecords2.getKiaraId());
//      talkRecordsVO.setKiaraName(byId.getName());
//      talkRecordsVO.setKiaraImgUrl(byId.getImgurl());
//      SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//      simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
//      talkRecordsVO.setPostTime(simpleDateFormat.format(talkRecords2.getPostTime()));
//
//      JSONObject textt=JSONUtil.parseObj(talkRecordsVO);
//      String tttt=JSONUtil.toJsonStr(textt);
//
//      //遍历HashMap
//      for (String key : webSocketSet.keySet()) {
//          try {
//              //判断接收用户是否是当前发消息的用户
//
//              webSocketSet.get(key).sendMessage(tttt);
//
//          } catch (IOException e) {
//              e.printStackTrace();
//          }
//      }


      userno = userId.toString();//接收到发送消息的人员编号
    this.session = session;
    webSocketSet.put(userno, this);//加入map中
    System.out.println("连接成功 当前用户id为  "+userno);
  }

  /**
   * 连接关闭
   *
   * @param
   */
  @OnClose
  public void onClose() {

//      Integer useridd=Integer.parseInt(userId);
//      TalkRecords talkRecords=new TalkRecords();
//      talkRecords.setStatus(2);
////      talkRecords.setContent("进入了聊天室");
//      TalkRecords talkRecords1=new TalkRecords();
//      BeanUtils.copyProperties(talkRecords,talkRecords1);
//      Long randowid=System.currentTimeMillis();
//      Integer uuid= randowid.intValue();
//      talkRecords1.setId(uuid);
//      talkRecords1.setUserId(useridd);
//      talkRecords1.setPostTime(new Date());
//      talkRecords1.setKiaraId(loginDao.findUserKiaraId(useridd));
//      TalkKiara byId2 = talkKiaraService.getById(talkRecords1.getKiaraId());
//      talkRecords1.setContent(byId2.getName()+" 离开聊天室");
//
//      boolean save = talkRecordsService.save(talkRecords1);
//      TalkRecords talkRecords2=talkRecordsService.getById(uuid);
//
//      TalkRecordsVO talkRecordsVO=new TalkRecordsVO();
//      talkRecordsVO.setId(talkRecords2.getId());
//      talkRecordsVO.setContent(talkRecords2.getContent());
//      talkRecordsVO.setStatus(talkRecords2.getStatus());
//      talkRecordsVO.setKiaraId(talkRecords2.getKiaraId());
//      talkRecordsVO.setUserId(talkRecords2.getUserId());
//      TalkKiara byId = talkKiaraService.getById(talkRecords2.getKiaraId());
//      talkRecordsVO.setKiaraName(byId.getName());
//      talkRecordsVO.setKiaraImgUrl(byId.getImgurl());
//      SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//      simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
//      talkRecordsVO.setPostTime(simpleDateFormat.format(talkRecords2.getPostTime()));
//
//      JSONObject textt=JSONUtil.parseObj(talkRecordsVO);
//      String tttt=JSONUtil.toJsonStr(textt);
//
//      //遍历HashMap
//      for (String key : webSocketSet.keySet()) {
//          try {
//              //判断接收用户是否是当前发消息的用户
//
//              webSocketSet.get(key).sendMessage(tttt);
//
//          } catch (IOException e) {
//              e.printStackTrace();
//          }
//      }
    if (!userno.equals("")) {
        Integer userKiaraId = loginDao.findUserKiaraId(Integer.valueOf(userno));
        redisService.deleteOnlineUser(userKiaraId);

      webSocketSet.remove(userno);  //从set中删除

    }
    System.out.println("连接关闭 用户id为  "+userno);
  }

  /**
   * 接收到消息
   *
   * @param text
   */
  @OnMessage
  public void onMsg(Session session, String text) throws IOException {
//    System.out.println(text.toString());

    sendAll(session,text);


  }
  /**
   * 给所有人发消息
   * @param message
   */
  private void sendAll(Session session,String message) {
    MessageText messageText=JSONUtil.toBean(message, MessageText.class);
TalkRecords talkRecords=new TalkRecords();
talkRecords.setStatus(messageText.getStatus());
talkRecords.setContent(messageText.getContent());
    Integer userId1= messageText.getUserId();
    TalkRecords talkRecords1=new TalkRecords();
    BeanUtils.copyProperties(talkRecords,talkRecords1);

      Snowflake snowflake = IdUtil.createSnowflake(1, 1);
      long uuid = snowflake.nextId();
    talkRecords1.setId(uuid);
    talkRecords1.setUserId(userId1);
    talkRecords1.setPostTime(new Date());
    talkRecords1.setKiaraId(loginDao.findUserKiaraId(userId1));
    boolean save = talkRecordsService.save(talkRecords1);
      TalkRecords talkRecords2=talkRecordsService.getOne(new LambdaQueryWrapper<TalkRecords>().eq(TalkRecords::getId,uuid));

      TalkRecordsVO talkRecordsVO=new TalkRecordsVO();
      talkRecordsVO.setId(talkRecords2.getId());
      talkRecordsVO.setContent(talkRecords2.getContent());
      talkRecordsVO.setStatus(talkRecords2.getStatus());
      talkRecordsVO.setKiaraId(talkRecords2.getKiaraId());
      talkRecordsVO.setUserId(talkRecords2.getUserId());
      TalkKiara byId = talkKiaraService.getById(talkRecords2.getKiaraId());
      talkRecordsVO.setKiaraName(byId.getName());
      talkRecordsVO.setKiaraImgUrl(byId.getImgurl());
      SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
      talkRecordsVO.setPostTime(simpleDateFormat.format(talkRecords2.getPostTime()));





    JSONObject textt=JSONUtil.parseObj(talkRecordsVO);
    String tttt=JSONUtil.toJsonStr(textt);

    //遍历HashMap
    for (String key : webSocketSet.keySet()) {
      try {
        //判断接收用户是否是当前发消息的用户

          webSocketSet.get(key).sendMessage(tttt);

      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  public void sendMessage(String message) throws IOException {
    this.session.getBasicRemote().sendText(message);
    //this.session.getAsyncRemote().sendText(message);
  }


}
